<template>
  <card-page>
    <el-form
      ref="form"
      :model="form" 
      label-width="80px"
    >
      <el-form-item v-if="parentCategory" label="分类">
        {{parentCategory.name}}
      </el-form-item>
      <el-form-item prop="title" label="标题" :rules="[{required: true, message: ' '}]">
        <el-input v-model.trim="form.title" autofocus style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="内容" :rules="[{required: true, message: ' '}]">
        <quill-editor
          ref="editor"
          v-model="form.content"
          :options="editorOptions"
          @ready="onEditorReady($event)"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="submitting">确定</el-button>
      </el-form-item>
    </el-form>
  </card-page>
</template>

<script>
import { quillEditor, Quill } from 'vue-quill-editor';
import { container, ImageExtend, QuillWatch } from 'quill-image-extend-module';
import 'quill/dist/quill.snow.css';

Quill.register('modules/ImageExtend', ImageExtend);

export default {
  pageProps: {
    title: '编辑图文知识'
  },
  components: {
    quillEditor
  },
  data() {
    return {
      form: {
        categoryId: this.$params.parentCategory && this.$params.parentCategory.id,
        resourceType: 2,
        title: '',
        content: '',
        url: '',
        ...this.$params.resource
      },
      submitting: false,
      parentCategory: this.$params.parentCategory,
      editorOptions: {
        modules: {
          ImageExtend: {
            loading: true,
            name: 'file',
            action: '/api/util/upload',
            response: res => res.data.url
          },
          toolbar: {
            container,
            handlers: {
              'image': function() {
                QuillWatch.emit(this.quill.id);
              }
            }
          }
        }
      }
    };
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;
        this.submitting = true;
        const ret = await this.$http[this.$params.resource ? 'put' : 'post']('/api/kbase/resource', this.form);
        if (ret.success) {
          this.$message.success('提交成功');
          this.$params.onSuccess();
        }
        this.submitting = false;
      });
    }
  }
}
</script>